package com.tica.it.itmanage.config.shiro;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tica.catool.exception.BusinessException;
import com.tica.it.itmanage.config.jwt.JwtUtil;
import com.tica.it.itmanage.config.jwt.ShiroJwtToken;
import com.tica.it.itmanage.core.domain.security.UserEntity;
import com.tica.it.itmanage.core.dto.UserDTO;
import com.tica.it.itmanage.core.dto.UserDetailDTO;
import com.tica.it.itmanage.server.user.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashSet;


@Slf4j
@Component
public class CustomerRealm extends AuthorizingRealm {


    @Autowired
    UserService userService;

    /**
     * 设置对应的token类型
     * 必须重写此方法，不然Shiro会报错
     *
     * @param token 令牌
     * @return boolean
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof ShiroJwtToken;
    }

    /**
     * 获取权限
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //权限认证
        log.info("开始进行权限认证.............");
        //获取用户名
        String token = (String) SecurityUtils.getSubject().getPrincipal();
        String username = JwtUtil.getUsername(token);
        //模拟数据库校验,写死用户名xsy，其他用户无法登陆成功
        if (!"xsy".equals(username)) {
            return null;
        }
        //创建授权信息
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //创建set集合，存储权限
        HashSet<String> rootSet = new HashSet<>();
        //添加权限
        rootSet.add("user:show");
        rootSet.add("user:admin");
        //设置权限
        info.setStringPermissions(rootSet);
        //返回权限实例
        return info;
    }

    /**
     * 登陆判断
     *
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        log.info("开始身份认证.....................");
        //获取token
        String token = (String) authenticationToken.getCredentials();
        //创建字符串，存储用户信息
        String username = null;
        //获取用户名
        username = JwtUtil.getUsername(token);
        UserEntity user = userService.getOne(new LambdaQueryWrapper<UserEntity>().eq(UserEntity::getUsername, username));
        if (user == null) {
            throw new BusinessException(10001, username + "用户不存在");
        }

        // 校验token是否超时失效 & 或者账号密码是否错误
//        if (!jwtTokenRefresh(token, username)) {
//            throw new AuthenticationException("Token失效，请重新登录!");
//        }
        //返回身份认证信息
        return new SimpleAuthenticationInfo(token, token, this.getName());


    }

    /**
     * jwt刷新令牌
     *
     * @param token    令牌
     * @param userName 用户名
     * @param passWord 通过单词
     * @return boolean
     */
//    public boolean jwtTokenRefresh(String token, String userName, String passWord) {
//        String redisToken = (String) redisTemplate.opsForValue().get(token);
//        if (redisToken != null) {
//            if (!JwtUtil.verify(redisToken, userName)) {
//                String newToken = JwtUtil.sign(userName);
//                //设置redis缓存
//                redisTemplate.opsForValue().set(token, newToken, expireTime * 2 / 1000, TimeUnit.SECONDS);
//            }
//            return true;
//        }
//        return false;
//    }
}
